#include "GameForcedResults.h"

static const int32 RESULT_MIN     = 0;    // Min result value in Keno
static const int32 RESULT_MAX     = 79;   // Max result value in Keno
static const int32 RESULT_INVALID = -1;   // Invalid result value


GameForcedResults::GameForcedResults()
{
	// Initialize indexes
	total   = 0;
	current = -1;
	results = 0;

	// Set range of valid values
	range.min = RESULT_MIN;
	range.max = RESULT_MAX;
}

GameForcedResults::~GameForcedResults()
{
	delete [] results;
	results = 0;
}

bool8 GameForcedResults::isEmpty()
{
	return (bool8)(total == 0);
}

int32 GameForcedResults::getTotal()
{
	return total;
}

bool8 GameForcedResults::load(String data)
{
	bool8 isLoaded = false;

	// Load results from string
	int32 length = data.getLength();
									
	// Check that we received an even number of digits			
	if (length > 0 && length % 2 == 0)
	{
		total = length / 2; 
		results = new int32[total];
		int j = 0;
										
		// Populate results list				
		for (int32 i = 0; i < total; i++)
		{
			results[i] = encodeResult(data.substring(j, 2));
			j += 2;

			// Check that the result value is correct					
			if (results[i] == RESULT_INVALID)
			{
				total--; // Reduce the list size
				i--;
			}
		}

		// Return true only if one result at least was loaded							
		if (total > 0)
		{
			isLoaded = true;
			current  = 0 ;

			String loaded, l;
			for (int i = 0; i < total; i++)
			{
				l.sprintf("%d ", results[i] + 1);
				loaded += l;
			}

			DEBUGMSG(("%ld forced results loaded: %S", total, (const wchar_t*)loaded));
		}
	}

	return isLoaded;
}

bool8 GameForcedResults::getNext(int32& result)
{
	bool8 next = false;

	if (total > 0 && current >= 0 && current <= total - 1)
	{
		result = results[current++];
		next   = true;
	}

	return next;
}

void GameForcedResults::resetIndex()
{
	current = (total > 0) ? 0 : -1;
}

int32 GameForcedResults::encodeResult(String decoded)
{
	int32 result = (decoded.toInt32());
	
	if (result < range.min || result > range.max)
		result = RESULT_INVALID;
	
	return result;
}